package cn.zj.smart.excel;

import cn.hutool.poi.excel.ExcelUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.*;

/**
 * @author xi.yang
 * @create 2021-11-02 15:36
 **/
public class ExcelUtils {
    public static <T> List<T> readExcel(String path, Class<T> clazz,int titleLine) {
        List<T> result = new ArrayList<>();
        List<List<Object>> allLines = ExcelUtil.getReader(path).read();
        // 标题
        Map<String, Integer> header = new HashMap<>();
        List<Object> headerLine = allLines.get(titleLine - 1);
        Field[] fields = clazz.getDeclaredFields();
        Set<String> fieldNames = new HashSet<>();
        for (Field field : fields) {
            fieldNames.add(field.getName());
        }
        for (int i = 0; i < headerLine.size(); i++) {
            String headStr = headerLine.get(i).toString();
            if (headStr.startsWith("_")) {
                continue;
            }
            header.put(headStr, i);
        }
        try {
            for (int i = titleLine; i < allLines.size(); i++) {
                T t = clazz.newInstance();
                for (Field field : fields) {
                    String fieldName = field.getName();
                    Integer index = header.get(fieldName);
                    if (index == null) {
                        continue;
                    }
                    field.setAccessible(true);
                    Object obj = allLines.get(i).get(index);
                    Type type = field.getType();
                    if (int.class.equals(type) || Integer.class.equals(type)) {
                        field.set(t, Integer.parseInt(obj.toString()));
                    } else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
                        field.set(t, "1".equals(obj.toString()));
                    } else {
                        field.set(t, obj);
                    }
                }
                result.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
